<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="危废名称" prop="wasteName">
                <el-input v-model="queryParams.wasteName" placeholder="请输入危废名称" clearable size="small" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="批次号码" prop="batchNumber">
                <el-input v-model="queryParams.batchNumber" placeholder="请输入批次号码" clearable size="small" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label-width="100px" label="出库操作者" prop="outOperator">
                <el-input v-model="queryParams.outOperator" placeholder="请输入操作者姓名" clearable size="small" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="出库日期">
                <el-date-picker v-model="daterangeOutDate" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="危废仓库" prop="warehouseId">
                <el-select v-model="queryParams.warehouseId" placeholder="请选择仓库">
                    <el-option v-for="item in warehouseList" :label="item.warehouseName" :key="item.warehouseId" :value="item.warehouseId" />
                </el-select>
            </el-form-item>
            <el-form-item label="处置方式" prop="handleMethod">
                <el-select v-model="queryParams.handleMethod" placeholder="请选择处置方式">
                    <el-option v-for="item in wasteHandlerMethodList" :label="item.dictLabel" :key="item.dictValue" :value="item.dictValue" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" :loading="exportLoading" @click="handleExport" v-hasPermi="['business:outWarehouse:export']">导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="outWarehouseList" @selection-change="handleSelectionChange">
            <!-- <el-table-column type="selection" width="55" align="center" /> -->
            <el-table-column label="危废收运ID" align="center" prop="wasteCollectId" v-if="false" />
            <el-table-column label="批次号码" align="center" prop="batchNumber" width="180" />
            <el-table-column type="expand">
                <template slot-scope="props">
                    <keep-alive>
                        <waste-info-card :row="props.row" />
                    </keep-alive>
                </template>
            </el-table-column>
            <el-table-column label="危废名称" align="left" prop="wasteName" />
            <el-table-column label="仓库名称" align="center" prop="warehouseName" />
            <el-table-column label="危废重量" align="center" prop="wasteWeight" />
            <el-table-column label="处置方式" align="center" prop="handleMethod" :formatter="handleMethodFormat" />
            <el-table-column label="出库日期" align="center" prop="outDate" width="180" />
            <el-table-column label="出库操作者" align="center" prop="outOperator" width="100" />
            <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleOut(scope.row)" v-hasPermi="['business:outWarehouse:edit']">出库</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['business:outWarehouse:remove']">删除</el-button>
                </template>
            </el-table-column> -->
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改危废出库对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="出库日期" prop="outDate">
                    <el-date-picker clearable size="small" v-model="form.outDate" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择出库日期">
                    </el-date-picker>
                </el-form-item>

                <el-divider content-position="center">危废出库明细信息</el-divider>
                <el-table :data="form.outWarehouseDetailList" ref="ewmsOutWarehouseDetail">
                    <el-table-column type="selection" width="50" align="center" />
                    <el-table-column label="序号" align="center" type="index" :index="1" width="50" />
                    <el-table-column label="危废名称" prop="wasteName">
                        <template slot-scope="scope">
                            <span>{{scope.row.wasteName}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="处置方式">
                        <template slot-scope="scope">
                            <!-- <span> <el-tag type="info">{{scope.row.warehouseName}}</el-tag></span> -->
                            <el-select v-model="scope.row.handleMethod" placeholder="请选择处置方式" @change="handlerMethodChangeHandler(scope.row)">
                                <el-option v-for="item in wasteHandlerMethodList" :label="item.dictLabel" :key="item.dictValue" :value="item.dictValue" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column label="处置公司">
                        <template slot-scope="scope">
                            <!-- <span> <el-tag type="info">{{scope.row.warehouseName}}</el-tag></span> -->
                            <el-select v-if="scope.row.handleMethod === 'out_factory'" v-model="scope.row.handleCompany" placeholder="请选择处置公司">
                                <el-option v-for="item in wasteHandleCompanyList" :label="item.dictLabel" :key="item.dictValue" :value="item.dictValue" />
                            </el-select>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listOutWarehouse, getOutWarehouse, delOutWarehouse, addOutWarehouse, updateOutWarehouse, exportOutWarehouse } from "@/api/business/outWarehouse";
import { listWarehouseForSelect } from "@/api/system/warehouse";
import WasteInfoCard from "@/views/business/wasteInfoCard";

import { mapActions } from "vuex";

export default {
    name: "OutWarehouseRecord",
    components: {
        WasteInfoCard
    },
    data() {
        return {
            //按钮loading
            buttonLoading: false,
            // 遮罩层
            loading: true,
            // 导出遮罩层
            exportLoading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 危废出库表格数据
            outWarehouseList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                outCode: undefined,
                outDate: undefined,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                outCode: [
                    { required: true, message: "出库编码不能为空", trigger: "blur" }
                ],
                outDate: [
                    { required: true, message: "出库日期不能为空", trigger: "blur" }
                ],
            },
            // 处置方式选项列表
            wasteHandlerMethodList: [],
            // 处置公司选项列表
            wasteHandleCompanyList: [],
            // 仓库列表
            warehouseList: [],
            // 出库日期范围
            daterangeOutDate: [],
        };
    },
    created() {
        this.getList();
        this.initDictData();
        this.getHandleMethodList();
        this.getHandleCompanyList();
        this.getWarehouseList();
    },
    methods: {
        ...mapActions({
            initDictData: "initDataForWasteInfoCard",
        }),
        /** 获取处置方式 */
        getHandleMethodList() {
            this.getDicts("waste_handler_method").then((response) => {
                this.wasteHandlerMethodList = response.data;
            });
        },
        /** 获取处置公司 */
        getHandleCompanyList() {
            this.getDicts("waste_handle_company").then((response) => {
                this.wasteHandleCompanyList = response.data;
            });
        },
        // 处置方式字典翻译
        handleMethodFormat(row, column) {
            return this.selectDictLabel(this.wasteHandlerMethodList, row.handleMethod);
        },
        // 获取仓库列表
        getWarehouseList() {
            listWarehouseForSelect().then(response => {
                this.warehouseList = response.data;;
            });
        },
        /** 查询危废出库列表 */
        getList() {
            this.loading = true;
            this.queryParams.params = {};
            if (null != this.daterangeOutDate && '' != this.daterangeOutDate) {
                this.queryParams.params["beginOutDate"] = this.daterangeOutDate[0];
                this.queryParams.params["endOutDate"] = this.daterangeOutDate[1];
            }
            listOutWarehouse(this.queryParams).then(response => {
                this.outWarehouseList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                outWarehouseId: undefined,
                outCode: undefined,
                outDate: this.parseTime(new Date()),
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.wasteInventoryId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 出库按钮操作 */
        handleOut(row) {
            this.reset();
            let wasteInventoryIds = [];
            if (row.wasteInventoryId) {
                wasteInventoryIds.push(row.wasteInventoryId);
            } else {
                wasteInventoryIds = this.ids;
            }
            this.form.outWarehouseDetailList = this.outWarehouseList.filter(item => wasteInventoryIds.indexOf(item.wasteInventoryId) != -1).map(item => {
                const newItem = {};
                newItem.wasteInventoryId = item.wasteInventoryId;
                newItem.wasteName = item.wasteName;
                newItem.wasteId = item.wasteId;
                return newItem;
            });
            this.open = true;
            this.title = "危废出库";
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加危废出库";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.loading = true;
            this.reset();
            const outWarehouseId = row.outWarehouseId || this.ids
            getOutWarehouse(outWarehouseId).then(response => {
                this.loading = false;
                this.form = response.data;
                this.open = true;
                this.title = "修改危废出库";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                // 出库明细校验
                for (let i = 0; i < this.form.outWarehouseDetailList.length; i++) {
                    const detailItem = this.form.outWarehouseDetailList[i];
                    if (detailItem.handleMethod === null || detailItem.handleMethod === undefined || detailItem.handleMethod === "") {
                        this.msgError("处置方式不能为空");
                        return false;
                    }
                    if (detailItem.handleMethod === 'out_factory' && !detailItem.handleCompany) {
                        this.msgError("处置公司不能为空");
                        return false;
                    }
                }
                if (valid) {
                    this.buttonLoading = true;
                    if (this.form.outWarehouseId != null) {
                        updateOutWarehouse(this.form).then(response => {
                            this.buttonLoading = false;
                            this.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        }).catch(err => this.buttonLoading = false);
                    } else {
                        addOutWarehouse(this.form).then(response => {
                            this.buttonLoading = false;
                            this.msgSuccess("出库成功");
                            this.open = false;
                            this.getList();
                        }).catch(err => this.buttonLoading = false);
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const outWarehouseIds = row.outWarehouseId || this.ids;
            this.$confirm('是否确认删除危废出库编号为"' + outWarehouseIds + '"的数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                this.loading = true;
                return delOutWarehouse(outWarehouseIds);
            }).then(() => {
                this.loading = false;
                this.getList();
                this.msgSuccess("删除成功");
            }).catch(() => { });
        },
        /** 导出按钮操作 */
        handleExport() {
            const queryParams = this.queryParams;
            this.$confirm('是否确认导出所有危废出库数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                this.exportLoading = true;
                return exportOutWarehouse(queryParams);
            }).then(response => {
                this.download(response.msg);
                this.exportLoading = false;
            }).catch(() => { });
        },
        /** 处置方式改变 */
        handlerMethodChangeHandler(row) {
            if (row.handleMethod === "incinerate") {
                if (row.handleCompany) {
                    row.handleCompany = undefined
                }
            }
        }
    }
};
</script>
<style>
.demo-table-expand {
    font-size: 0;
    padding: 0px 0px 0px 150px;
}
.demo-table-expand label {
    width: 90px;
    color: #99a9bf;
}
.demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
}
</style>